var win;
var socialTypeStore;
Ext.onReady(function() {
	Ext.QuickTips.init();
	Ext.form.Field.prototype.msgTarget = 'side';
	win=addSocialTypeInfo();
	
	var searchPanel = new Ext.form.FormPanel({
						frame : true,
						buttonAlign : 'right',
						title : "查询条件",
						id : 'employMessage',
						bodyStyle : 'padding:5px 5px 0',
						url : '',
						items : [{
									layout : 'column',
									items : [{
												columnWidth : .5,
												layout : 'form',
												items : [{
															fieldLabel : '类别编码',
															anchor : '90%',
															id : 'social_typecode',
															xtype : 'textfield'
														}]
											}, {
												columnWidth : .5,
												layout : 'form',
												items : [{
															fieldLabel : '类别名称',
															anchor : '90%',
															id : 'social_typename',
															xtype : 'textfield'
														}]
											}],
									buttons : [{
												text : '新增',
												id : '_btninsert',
												handler : function() {
													win.show();
												}
											}, {
												text : '查询',
												id : '_btnSearch',
												handler : function() {
													socialTypeStore.on('beforeload', function() {
																socialTypeStore.baseParams = {
																	'filter.typeCode' : Ext.getCmp('social_typecode').getValue(),
																	'filter.typeName' : Ext.getCmp('social_typename').getValue()
																}
															});
													socialTypeStore.load();
												}
											}, {
												text : '删除',
												id : '_btnDelete',
												handler : function() {
													socialTypeGrid.stopEditing();
											   		var selectRecords = socialTypeGrid.getSelectionModel().getSelections();
													var length = selectRecords.length;
												   	if (length < 1) {
														return;
													}
												   	Ext.MessageBox.show({
														title : '提示',
														msg : '您选中了' + length + '条记录进行删除,请问您确认吗?',
														buttons : Ext.MessageBox.OKCANCEL,
														fn : function(btn) {
															if (btn == "ok") {
																//判断是否能删开始
																var delIds = [], updIds = [], updNames = [];
																for (var index = 0; index < length; index++) {
																	if(selectRecords[index].data.social_security_id != -1){
																		updIds.push(selectRecords[index].data.social_typeid);
																		updNames.push(selectRecords[index].data.social_typename);
																	}else{
																		delIds.push(selectRecords[index].data.social_typeid);
																	}
																}
																//判断是否能删结束
																if (updIds.length>0) {
																	Ext.MessageBox.show({
																		title : '提示',
																		msg : "以下"+updIds.length+"种社保类别正在使用，不能删除： " + updNames.join("，\n")+"。 是否设置为无效?",
																		buttons : Ext.MessageBox.YESNO,
																		fn : function(btn) {
																			if (btn == "yes") {
																				Ext.Ajax.request({
																					url : "socialType!deletePbSocialType.action?delIds=" + delIds.join(",")+"&updIds="+updIds.join(","),
																					method : "post",
																					success : function(response, options) {
																						var responseTextVale = Ext.util.JSON.decode(response.responseText);
																						if(responseTextVale.hasSubCity>0){
																						   Ext.Msg.alert('删除失败', '失败原因！');
																						}else{
																							socialTypeStore.reload();
																							Ext.Msg.alert('提示', '删除操作成功！');
																						}
																						
																					}
																				});
																			}
																			if (btn == "no") {
																				return;
																			}
																		}
																	});
																}else{
																	Ext.Ajax.request({
																		url : "socialType!deletePbSocialType.action?delIds=" + delIds.join(","),
																		method : "post",
																		success : function(response, options) {
																			var responseTextVale = Ext.util.JSON.decode(response.responseText);
																			if(responseTextVale.hasSubCity>0){
																			   Ext.Msg.alert('删除失败', '失败原因！');
																			}else{
																				socialTypeStore.reload();
																				Ext.Msg.alert('提示', '删除操作成功！');
																			}
																			
																		}
																	});
																}
															}
															if (btn == "cancel") {
																return;
															}
														}
													});
												}
										}]
								}]
					});

			searchPanel.render(Ext.getBody());
			
	// 数据源
	socialTypeStore = new Ext.data.Store({
				url : 'socialType!QueryPbSocialTypeResult.action',
				reader : new Ext.data.JsonReader({
							root : 'result.result',
							id:'social_typeid',
							totalProperty : 'result.totalCount'
						}, [{
									name : 'social_typeid',
									mapping : 'social_typeid'
								}, {
									name : 'social_security_id',
									mapping : 'social_security_id'
								}, {
									name : 'social_typename',
									mapping : 'social_typename'
								}, {
									name : 'is_valid',
									mapping : 'is_valid',
									type:'bool'
						}]),  
			            listeners: {   
			                'update': function(thiz, record, operation){      //捕捉记录发生更改的事件   
			                    var pbSocialType = thiz.getAt(thiz.indexOf(record)).data;   //获得当前修改后的记录  
									//有trim的公共方法吗
								if (pbSocialType.social_typename==""||pbSocialType.social_typename==''||pbSocialType.social_typename==null) {
									thiz.rejectChanges(); 
									return;
								}
			                    if(operation == Ext.data.Record.EDIT){              //判断update时间的操作类型是否为 edit 该事件还有其他操作类型比如 commit,reject   
			                        Ext.Ajax.request({   
			                            url: 'socialType!updatePbSocialType.action',                   //修改用户数据   
			                            params: {                                   //获取修改后的用户数据传到服务器   
			                                'pbSocialType.social_typeid': pbSocialType.social_typeid,  
			                                //'pbSocialType.social_typecode': pbSocialType.social_typecode,                
			                                'pbSocialType.social_typename': pbSocialType.social_typename,   
			                                'pbSocialType.is_valid': pbSocialType.is_valid
			                            },    
			                            success: function(response, opts) {   
			                                thiz.commitChanges();                   //如果请求成功则更新本地记录:)   
			                            },   
			                            failure: function(response, opts) {   
			                                Ext.Msg.alert('错误','server-side failure with status code ' + response.status);   
			                                thiz.rejectChanges();                   //请求失败,回滚本地记录:)   
			                            }   
			                        });   
			                    }   
			                }   
			            } 
			});

	// 查询显示的表格
	var checkColumn = new Ext.grid.CheckColumn({    
        header: '是否有效',    
        dataIndex: 'is_valid',    
        width: 60    
     });  
	var sm = new Ext.grid.CheckboxSelectionModel();
	var cm = new Ext.grid.ColumnModel([new Ext.grid.RowNumberer(), sm, {
			header : '类别编码',
				dataIndex : 'social_typeid'
			},{
				header : '类别速记码',
				dataIndex : 'social_security_id',
				hidden : true
			}, {
				header : '类别名称',
				dataIndex : 'social_typename',
	            editor: new Ext.form.TextField({
							blankText:'请输入类型编码!',
							allowBlank:false
	            })
			},checkColumn]);

	var socialTypeGrid = new Ext.grid.EditorGridPanel({
				id : 'pbEmp',
				height : document.body.clientHeight
						- Ext.getCmp('employMessage').getInnerHeight()
						- Ext.getCmp('employMessage').getFrameHeight(),
				trackMouseOver:true, 
				stripeRows:true, 
				autoScroll:true, 
				hideCollapseTool:true, 
				collapsible:true, 
				titleCollapse:true, 
				bufferResize:true, 
				loadMask:true, 
				plugins:checkColumn,    
				clicksToEdit:1,
				bbar : new Ext.PagingToolbar({
							pageSize : pageSize,
							store : socialTypeStore,
							displayInfo : true,
							dispalyMsg : '显示第{0}条到{1}条记录，一共{2}条',
							emptyMsg : '没有记录'
						}),
				sm : sm,
				cm : cm,
				store : socialTypeStore,
				loadMask : true,
				loadMask : {
					msg : '正在加载数据...'
				}
			});

	socialTypeStore.load();
	socialTypeGrid.render(Ext.getBody());
});